package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantFields;
import cn.yuanqiao.archive.appManager.mapper.TenantFieldsMapper;
import cn.yuanqiao.archive.appManager.service.ITenantFieldsService;
import cn.yuanqiao.archive.chengguojieshou.mapper.YqdaarticulatedMapper;
import cn.yuanqiao.common.constant.SysContants;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.bean.BeanValidators;
import cn.yuanqiao.common.utils.sql.YqDatabaseSQLUtil;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.Date;
import java.util.List;

@Service
public class TenantFieldsServiceImpl implements ITenantFieldsService {
    private static final Logger log = LoggerFactory.getLogger(TenantFieldsServiceImpl.class);

    @Autowired
    private TenantFieldsMapper tenantFieldsMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private YqdaarticulatedMapper yqdaarticulatedMapper;
    @Resource
    private YqDatabaseIdProvider yqDatabaseIdProvider;
    /**
     * 查询基础数据
     *
     * @param ID 基础数据主键
     * @return 基础数据
     */
    @Override
    public TenantFields selectyqfieldsByID(String ID)
    {
        TenantFields tenantFields = new TenantFields();
        return tenantFieldsMapper.selectTenantFieldsByID(ID,tenantFields.getTableName());
    }

    /**
     * 查询基础数据列表
     *
     * @param yqfields 基础数据
     * @return 基础数据
     */
    @Override
    public List<TenantFields> selectyqfieldsList(TenantFields yqfields)
    {
        Date createTime = yqfields.getCreateTime();
        Date createTime2 = yqfields.getCreateTime2();
        if(createTime!=null){
            int i = createTime.compareTo(createTime2);
            if(i==0){
                createTime2.setHours(24);
            }
        }
        String fieldName = yqfields.getFieldName();
        if(StringUtils.isNotEmpty(fieldName) && !"null".equals(fieldName)){
            yqfields.setFieldName(fieldName.toUpperCase());
        }
        return tenantFieldsMapper.selectTenantFieldsList(yqfields);
    }

    /**
     * 新增基础数据
     *
     * @param yqfields 基础数据
     * @return 结果
     */
    @Override
    public int insertyqfields(TenantFields yqfields)
    {
        String databaseId =  yqDatabaseIdProvider.getDatabaseId();
        String single = null;
        if(DbIdEnum.DM.getCode().equalsIgnoreCase(databaseId)){
            single = yqdaarticulatedMapper.getSingle("SELECT "+ YqDatabaseSQLUtil.YQ_WM_CONCAT("KEYWORD") +" FROM V$RESERVED_WORDS");
        }else {
            single = SysContants.KEYWORDS;
        }
        if(single!=null){
            String fieldName = yqfields.getFieldName();
            single = ","+single+",";
            if(single.contains(","+fieldName+",")){
                throw new ServiceException(fieldName+"为系统关键字禁止添加");
            }
        }

        yqfields.setCreateTime(DateUtils.getNowDate());
        TenantFields tenantFields = new TenantFields();
        tenantFields.setType(yqfields.getType());
        tenantFields.setFieldName(yqfields.getFieldName());
        List<TenantFields> tenantFields1 = tenantFieldsMapper.selectTenantFieldsList(tenantFields);
        if(tenantFields1.size()>0){
            for(TenantFields tenantFields2:tenantFields1){
                if(tenantFields2.getFieldName().equals(yqfields.getFieldName())){
                    throw new ServiceException("该字段名称已存在！");
                }
            }
        }
        return tenantFieldsMapper.insertTenantFields(yqfields);
    }

    /**
     * 修改基础数据
     *
     * @param yqfields 基础数据
     * @return 结果
     */
    @Override
    public int updateyqfields(TenantFields yqfields)
    {
        return tenantFieldsMapper.updateTenantFields(yqfields);
    }

    /**
     * 批量删除基础数据
     *
     * @param IDs 需要删除的基础数据主键
     * @return 结果
     */
    @Override
    public int deleteyqfieldsByIDs(String[] IDs)
    {
        TenantFields tenantFields = new TenantFields();
        return tenantFieldsMapper.deleteTenantFieldsByIDs(IDs,tenantFields.getTableName());
    }

    /**
     * 删除基础数据信息
     *
     * @param ID 基础数据主键
     * @return 结果
     */
    @Override
    public int deleteyqfieldsByID(String ID)
    {
        TenantFields tenantFields = new TenantFields();
        return tenantFieldsMapper.deleteTenantFieldsByID(ID,tenantFields.getTableName());
    }

    @Override
    public String importUser(List<TenantFields> userList, Boolean isUpdateSupport, String operName, String type)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入元数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (TenantFields fields : userList)
        {
            try
            {
                fields.setType(type);
                int i = tenantFieldsMapper.selectyqfieldsCount(fields);
                if(0==i){
                    BeanValidators.validateWithException(validator, fields);
                    fields.setCreateBy(operName);
                    fields.setCreateTime(DateUtils.getNowDate());

                    tenantFieldsMapper.insertTenantFields(fields);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、导入成功");
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、字段 " + fields.getFieldName() + " 已存在");
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
